var express = require('express');
var router = express.Router();
const UserModel = require('../model/UserModel')

/* GET users listing. */
router.get('/', function(req, res, next) {
  // 读取前端的cookie
  // req.cookies
  // 设置前端的cookie
  res.cookie('gender','mela')
  res.send('respond with a resource');
});

router.get('/user/del/:id',(req,res) => {
  console.log(req.params.id)
  UserModel.deleteOne({_id: req.params.id}).then(data => {
    console.log(data)
    res.send(
      {ok:1}
    )
  })

})

router.get('/user/list',(req,res) => {
  const {page, limit} = req.query
  // UserModel.find() 查所有
  UserModel.find({},['username,age']).sort({age:-1}).skip((page-1)*limit).limit(limit)
  .then(data => {
    res.send(data)
  })
})

router.post("/user/add",(req,res) => {
  console.log(req.body)
  // 插入数据库
  // 创建数据库（user,限制类型）
  const {username,password,age} = req.body
  UserModel.create({
    username,password,age
  }).then(data => {
    console.log(data)
    res.send({ok:1})
  }).catch(err => {
    res.send({ok:0})
  })
})


router.post('/user/update/:id',(req,res) => {
  console.log(req.body,req.params)
  const {username} = req.body
  UserModel.updateOne({_id:req.params.id}, { 
    username
  }).then(data => {
    console.log(data)
    res.send({
      ok:1
    })
  }).catch(err => {
    console.log(err)
  })
})

module.exports = router;
